import { login, logout, getInfo, getSystemParams } from '@/api/login'
import {
  getUser,
  getMenu,
  getGroup,
  getProject,
  getToken,
  getWebsiteId,
  getSystemType,
  removeUserInfo,
  setUserInfo
} from '@/utils/auth'
import { addRoutes, filterMenu } from '@/permission.js'
import { getUserInfo, winOut } from '@/utils/auth'

const user = getUser()
const group = getGroup()
const menu = getMenu()
const project = getProject()

export default {
  state: {
    token: getToken(),
    systemType: getSystemType(),
    userName: user && user.userName,
    userNo: user && user.userNo,
    userId: user && user.userId,
    userGrade: user && user.userGrade,
    email: user && user.email,
    telephone: user && user.telephone,
    avatar: user && user.avatar,
    iconFilePath: user && user.iconFilePath,
    groupId: group && group.groupId,
    groupName: group && group.groupName,
    projectId: project && project.projectId,
    projectName: project && project.projectName,
    roles: [],
    websiteId: getWebsiteId(),
    menu,
    systemName: '权限管理平台',
    systemVersion: process.env.VUE_APP_VERSION,
    enabledDatagroup: process.env.VUE_APP_ENABLED_DATAGROUP || '0'
  },
  getters: {
    groupId: state => state.groupId,
    groupName: state => state.groupName,
    token: state => state.token,
    name: state => state.userName,
    userNo: state => state.userNo,
    userId: state => state.userId,
    userGrade: state => state.userGrade,
    email: state => state.email,
    telephone: state => state.telephone,
    iconFilePath: state => state.iconFilePath,
    projectId: state => state.projectId,
    projectName: state => state.projectName,
    systemType: state => state.systemType,
    roles: state => state.roles,
    websiteId: state => state.websiteId,
    menu: state => {
      return [
        {
          id: 0,
          text: '首页',
          url: '/dashboard'
        }
      ].concat(state.menu)
    },
    systemName: state => state.systemName,
    systemVersion: state => state.systemVersion,
    enabledDatagroup: state => state.enabledDatagroup
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER: (
      state,
      { userNo, userName, userId, userGrade, email, telephone, iconFilePath }
    ) => {
      state.userNo = userNo || ''
      state.userName = userName || ''
      state.userId = userId || 0
      state.userGrade = userGrade || null
      state.email = email || ''
      state.telephone = telephone || ''
      state.iconFilePath = iconFilePath || ''
    },
    SET_USERNO: (state, userNo) => {
      state.userNo = userNo || ''
    },
    SET_GROUP: (state, { groupId, groupName }) => {
      state.groupId = groupId
      state.groupName = groupName
    },
    SET_PROJECT: (state, { projectId, projectName }) => {
      state.projectId = projectId
      state.projectName = projectName
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles || []
    },
    SET_MENU: (state, menu) => {
      state.menu = menu
      addRoutes(menu)
    },
    SET_SYSTEMTYPE: (state, systemType) => {
      state.systemType = systemType
    },
    SET_WEBSITEID: (state, websiteId) => {
      state.websiteId = websiteId
    },
    SET_SYSTEM_NAME: (state, systemName) => {
      state.systemName = systemName
    },
    SET_SYSTEM_VERSION: (state, systemVersion) => {
      state.systemVersion = systemVersion
    },
    SET_ENABLED_DATAGROUP: (state, enabledDatagroup) => {
      state.enabledDatagroup = enabledDatagroup
    }
  },

  actions: {
    // 获取系统信息
    GetSystemParmas({ commit }) {
      return new Promise((resolve, reject) => {
        getSystemParams()
          .then(({ data }) => {
            data &&
              data.map(item => {
                // 系统名称
                if (item.code === 'system-name') {
                  commit('SET_SYSTEM_NAME', item.codeValue)
                }
                if (item.code === 'system-version') {
                  // 系统版本
                  commit('SET_SYSTEM_VERSION', item.codeValue)
                }
                // 是否开启数据组
                if (item.code === 'enabled_datagroup') {
                  commit('SET_ENABLED_DATAGROUP', item.codeValue)
                }
              })
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(
          username,
          userInfo.password,
          userInfo.projectId,
          userInfo.randomCode,
          userInfo.randomCodeKey
        )
          .then(({ data }) => {
            // 处理后端字段传过来是 accessToken (jar包字段，只能统一平台去修改) 前端使用的是 accesstoken
            const token = data.token
            commit('SET_TOKEN', token)
            commit('SET_USER', data.user)
            commit('SET_GROUP', data.group)
            commit('SET_MENU', data.functionTreeList.filter(filterMenu))
            commit('SET_SYSTEMTYPE', data.systemType)
            if (data.project) commit('SET_PROJECT', data.project)
            setUserInfo(data)
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    UrlAccesstokenLogin({ commit }, data) {
      const token = data.token
      const websiteId = data.websiteId
      console.log(websiteId, 'UrlAccesstokenLogin:::::::')
      commit('SET_TOKEN', token)
      commit('SET_USER', data.user)
      commit('SET_GROUP', data.group)
      commit('SET_MENU', data.functionTreeList)
      commit('SET_SYSTEMTYPE', data.systemType)
      commit('SET_WEBSITEID', websiteId)
      if (data.project) commit('SET_PROJECT', data.project)
      setUserInfo(data)
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        if (!state.userNo) {
          reject('error')
        }
        getInfo(state.userNo)
          .then(data => {
            const user = data[0]
            commit('SET_ROLES', user.roles)
            commit('SET_NAME', user.userName)
            commit('SET_AVATAR', user.avatar)

            resolve(user)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    SetUserInfo({ commit }, userNo) {
      const userInfo = getUserInfo()
      userInfo.user.userNo = userNo
      commit('SET_USERNO', userNo)
      setUserInfo(userInfo)
    },

    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            commit('SET_WEBSITEID', '')
            // 使用该方法进行退出
            winOut()
            removeUserInfo()
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeUserInfo()
        resolve()
      })
    }
  }
}
